package com.dianxin.smartpark.service.attendance.impl;

import com.chinatelecom.response.common.CommonResponseBody;
import com.chinatelecom.response.constant.ErrMsgEnum;
import com.chinatelecom.response.utils.BeanUtil;
import com.chinatelecom.response.utils.ResponseBodyWrapperUtil;
import com.dianxin.smartpark.dao.dataobject.attendance.*;
import com.dianxin.smartpark.dao.mapper.attendance.SmartParkAttendanceApproveMapper;
import com.dianxin.smartpark.dao.mapper.attendance.SmartParkAttendanceRecordMapper;
import com.dianxin.smartpark.dao.mapper.attendance.SmartParkAttendanceUserOccupyMapper;
import com.dianxin.smartpark.dao.qo.attendance.SmartParkAttendanceApproveQO;
import com.dianxin.smartpark.service.attendance.SmartParkAttendanceApproveService;
import com.dianxin.smartpark.service.utils.DateTimeUtil;
import com.dianxin.smartpark.service.vo.attendance.SmartParkAttendanceApproveVO;
import org.apache.commons.lang3.StringUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Date;
import java.util.List;

/**
 * @program: smart-park
 * @description: 考勤审批
 * @author: chenyong
 * @create: 2021-08-10 16:39
 */
@Service
public class SmartParkAttendanceApproveServiceImpl implements SmartParkAttendanceApproveService {
    private final static Logger logger = LoggerFactory.getLogger(SmartParkAttendanceApproveServiceImpl.class);

    @Resource
    private SmartParkAttendanceApproveMapper smartParkAttendanceApproveMapper;
    @Resource
    private SmartParkAttendanceUserOccupyMapper smartParkAttendanceUserOccupyMapper;
    @Resource
    private SmartParkAttendanceRecordMapper smartParkAttendanceRecordMapper;


    /**
     * 分页
     * @Description:  分页
     * @Author: ChenYong
     * @Date: 2021/8/10 0010
     * @param smartParkAttendanceApproveQO:
     * @Return: CommonResponseBody<List<SmartParkAttendanceApproveVO>>
     */
    @Override
    public CommonResponseBody<List<SmartParkAttendanceApproveVO>> getAttendanceApproves(SmartParkAttendanceApproveQO smartParkAttendanceApproveQO) {
        SmartParkAttendanceApproveExample recordExample = new SmartParkAttendanceApproveExample();
        SmartParkAttendanceApproveExample.Criteria criteria = recordExample.createCriteria();
        criteria.andIsDeletedEqualTo(0);
        if(StringUtils.isBlank(smartParkAttendanceApproveQO.getTenantId())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.EMPTY_PARAME.getErrorMessage(), ErrMsgEnum.EMPTY_PARAME.getErrorCode());
        }
        if (smartParkAttendanceApproveQO.getApproveStatus() != null) {
            criteria.andApproveStatusEqualTo(smartParkAttendanceApproveQO.getApproveStatus());
        }
        if (smartParkAttendanceApproveQO.getApproveType() != null) {
            criteria.andApproveTypeEqualTo(smartParkAttendanceApproveQO.getApproveType());
        }
        if (smartParkAttendanceApproveQO.getApprovePeople() != null) {
            criteria.andApprovePeopleEqualTo(smartParkAttendanceApproveQO.getApprovePeople());
        }
        if (StringUtils.isNotBlank(smartParkAttendanceApproveQO.getCreator())) {
            criteria.andCreatorEqualTo(smartParkAttendanceApproveQO.getCreator());
        }
        if (smartParkAttendanceApproveQO.getApproveStartTime() != null && smartParkAttendanceApproveQO.getApproveEndTime() !=null) {
            criteria.andApproveTimeBetween(smartParkAttendanceApproveQO.getApproveStartTime(),smartParkAttendanceApproveQO.getApproveEndTime());
        }
        if (smartParkAttendanceApproveQO.getNeedPage()) {
            recordExample.setOrderByClause("gmt_create desc limit " + (smartParkAttendanceApproveQO.getPageIndex() - 1) * smartParkAttendanceApproveQO.getPageSize() + "," + smartParkAttendanceApproveQO.getPageSize());
        } else {
            recordExample.setOrderByClause("gmt_create desc");
        }

        List<SmartParkAttendanceApprove> passRecords = smartParkAttendanceApproveMapper.selectByExample(recordExample);
        long count = smartParkAttendanceApproveMapper.countByExample(recordExample);

        return ResponseBodyWrapperUtil
                .successListWrapper(passRecords, count, smartParkAttendanceApproveQO, SmartParkAttendanceApproveVO.class);
    }

    /**
     * 新增
     * @Description:  新增
     * @Author: ChenYong
     * @Date: 2021/8/10 0010
     * @param smartParkAttendanceApproveQO:
     * @Return: CommonResponseBody
     */
    @Override
    public CommonResponseBody saveAttendanceApprove(SmartParkAttendanceApproveQO smartParkAttendanceApproveQO) {
        SmartParkAttendanceApprove smartParkAttendanceApprove = new SmartParkAttendanceApprove();
        try {

            if(StringUtils.isBlank(smartParkAttendanceApproveQO.getTenantId())){
                return ResponseBodyWrapperUtil.fail(ErrMsgEnum.EMPTY_PARAME.getErrorMessage(), ErrMsgEnum.EMPTY_PARAME.getErrorCode());
            }
            if(smartParkAttendanceApproveQO.getApproveType()==3){
                if(smartParkAttendanceApproveQO.getRepairCardRecordId()==null){
                    return ResponseBodyWrapperUtil.fail("补卡类型需要当前打卡记录的ID","1000001");
                }
            }
            //待审核状态
            smartParkAttendanceApproveQO.setApproveStatus(1);
            smartParkAttendanceApproveQO.setApproveOpinion("待审核");
            if("PC".equals(smartParkAttendanceApproveQO.getTerminalType())){
                //已完成状态
                smartParkAttendanceApproveQO.setApproveStatus(2);
                smartParkAttendanceApproveQO.setApproveOpinion("同意");
                smartParkAttendanceApproveQO.setApproveTime(new Date());
                //当前登录用户
                smartParkAttendanceApproveQO.setApprovePeople(1L);
            }

            BeanUtil.conversion(smartParkAttendanceApproveQO,smartParkAttendanceApprove);
            smartParkAttendanceApprove.beforeInsert();
            int insert = smartParkAttendanceApproveMapper.insert(smartParkAttendanceApprove);
            Long id = smartParkAttendanceApprove.getId();
            if("PC".equals(smartParkAttendanceApproveQO.getTerminalType())){
                //不是补卡的时候保存人员暂用表
                if(smartParkAttendanceApprove.getApproveType()!=3 && insert>0){
                    SmartParkAttendanceUserOccupy smartParkAttendanceUserOccupy = new SmartParkAttendanceUserOccupy();
                    smartParkAttendanceUserOccupy.setUserId(smartParkAttendanceApprove.getUserId());
                    smartParkAttendanceUserOccupy.setBusinessType(smartParkAttendanceApprove.getApproveType() == 1?"请假":"出差");
                    smartParkAttendanceUserOccupy.setStartTime(smartParkAttendanceApprove.getStartTime());
                    smartParkAttendanceUserOccupy.setBusinessId(smartParkAttendanceApprove.getId());
                    smartParkAttendanceUserOccupy.setTenantId(smartParkAttendanceApprove.getTenantId());
                    smartParkAttendanceUserOccupy.setEndTime(smartParkAttendanceApprove.getEndTime());
                    smartParkAttendanceUserOccupy.beforeInsert();
                    smartParkAttendanceUserOccupyMapper.insert(smartParkAttendanceUserOccupy);
                }

                //如果为补卡类型那么审批结束后修改考勤记录
                if(smartParkAttendanceApprove.getApproveType()==3){
                    if(smartParkAttendanceApprove.getApproveStatus()==2){
                        SmartParkAttendanceRecord smartParkAttendanceRecord = smartParkAttendanceRecordMapper.selectByPrimaryKey(smartParkAttendanceApprove.getRepairCardRecordId());
                        if(smartParkAttendanceRecord!=null){
                            smartParkAttendanceRecord.setClockInStatus(1);
                            smartParkAttendanceRecord.setClockInStatusName("补卡");
                            String[] splitStrings = smartParkAttendanceRecord.getShiftWorkTime().split(":");
                            String hour = splitStrings[0];
                            String minute = splitStrings[1];
                            Date handle = DateTimeUtil.handle(smartParkAttendanceRecord.getClockInTime(), Integer.valueOf(hour), Integer.valueOf(minute));
                            smartParkAttendanceRecord.setClockInTime(handle);
                            if(id != null){
                                smartParkAttendanceRecord.setSupplement(id);
                            }
                            smartParkAttendanceRecord.setAbnormalMinutes(0);
                            smartParkAttendanceRecord.beforeUpdate();
                            smartParkAttendanceRecordMapper.updateByPrimaryKey(smartParkAttendanceRecord);
                        }
                    }
                }
            }
            return ResponseBodyWrapperUtil.toResData(insert);

        } catch (Exception e) {
            logger.error("",e);
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_SYSTEM.getErrorMessage(),ErrMsgEnum.ERROR_SYSTEM.getErrorCode());
        }
    }

    /**
     * 修改
     * @Description:  修改
     * @Author: ChenYong
     * @Date: 2021/8/10 0010
     * @param smartParkAttendanceApproveQO:
     * @Return: CommonResponseBody
     */
    @Override
    public CommonResponseBody updateAttendanceApprove(SmartParkAttendanceApproveQO smartParkAttendanceApproveQO) {
        SmartParkAttendanceApprove smartParkAttendanceApprove = new SmartParkAttendanceApprove();
        if(StringUtils.isBlank(smartParkAttendanceApproveQO.getTenantId())){
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.EMPTY_PARAME.getErrorMessage(), ErrMsgEnum.EMPTY_PARAME.getErrorCode());
        }
        try {
            BeanUtil.conversion(smartParkAttendanceApproveQO,smartParkAttendanceApprove);
            smartParkAttendanceApprove.beforeUpdate();
            return ResponseBodyWrapperUtil.toResData(smartParkAttendanceApproveMapper.updateByPrimaryKey(smartParkAttendanceApprove));
        } catch (Exception e) {
            logger.error("",e);
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_SYSTEM.getErrorMessage(),ErrMsgEnum.ERROR_SYSTEM.getErrorCode());
        }
    }

    /**
     * 删除
     * @Description:  删除
     * @Author: ChenYong
     * @Date: 2021/8/10 0010
     * @param smartParkAttendanceApproveQO:
     * @Return: CommonResponseBody
     */
    @Override
    public CommonResponseBody deleteAttendanceApprove(SmartParkAttendanceApproveQO smartParkAttendanceApproveQO) {
        SmartParkAttendanceApprove smartParkAttendanceApprove =  smartParkAttendanceApproveMapper.selectByPrimaryKey(smartParkAttendanceApproveQO.getId());
        smartParkAttendanceApprove.setIsDeleted(1);
        smartParkAttendanceApprove.beforeUpdate();
        return ResponseBodyWrapperUtil.toResData(smartParkAttendanceApproveMapper.updateByPrimaryKey(smartParkAttendanceApprove));
    }

    /**
     * 详情
     * @Description:  详情
     * @Author: ChenYong
     * @Date: 2021/8/10 0010
     * @param smartParkAttendanceApproveQO:
     * @Return: CommonResponseBody
     */
    @Override
    public CommonResponseBody<SmartParkAttendanceApproveVO> AttendanceApproveDetails(SmartParkAttendanceApproveQO smartParkAttendanceApproveQO) {
        SmartParkAttendanceApproveVO smartParkAttendanceApproveVO = new SmartParkAttendanceApproveVO();
        try {
            SmartParkAttendanceApprove smartParkAttendanceApprove = smartParkAttendanceApproveMapper.selectByPrimaryKey(smartParkAttendanceApproveQO.getId());
            BeanUtil.conversion(smartParkAttendanceApprove,smartParkAttendanceApproveVO);
            return ResponseBodyWrapperUtil.successWrapper(smartParkAttendanceApproveVO);
        } catch (Exception e) {
            logger.error("",e);
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_SYSTEM.getErrorMessage(),ErrMsgEnum.ERROR_SYSTEM.getErrorCode());
        }
    }

    /**
     * 处理审批
     * @Description:
     * @Author: ChenYong
     * @Date: 2021/8/10 0010
     * @param smartParkAttendanceApproveQO:
     * @Return: CommonResponseBody
     */
    @Override
    public CommonResponseBody AttendanceApproveHandle(SmartParkAttendanceApproveQO smartParkAttendanceApproveQO) {
        SmartParkAttendanceApprove smartParkAttendanceApprove = new SmartParkAttendanceApprove();

        try {
            smartParkAttendanceApprove = smartParkAttendanceApproveMapper.selectByPrimaryKey(smartParkAttendanceApproveQO.getId());
            smartParkAttendanceApprove.setApproveOpinion(smartParkAttendanceApproveQO.getApproveOpinion());
            smartParkAttendanceApprove.setApproveStatus(smartParkAttendanceApproveQO.getApproveStatus());
            smartParkAttendanceApprove.beforeUpdate();
            if(smartParkAttendanceApprove.getApproveStatus()==1){
                smartParkAttendanceApprove.setApproveTime(null);
                smartParkAttendanceApprove.setApproveOpinion("");
            }
            smartParkAttendanceApprove.setApproveTime(new Date());
/*            String handleText = "";
            //1 待审核  2 已通过  3已驳回  4已撤销
            if(smartParkAttendanceApproveQO.getApproveStatus() == 1){
                handleText = "待审核";
            }else if(smartParkAttendanceApproveQO.getApproveStatus() == 2){
                handleText = "已通过";
            }else if(smartParkAttendanceApproveQO.getApproveStatus() == 3){
                handleText = "已驳回";
            }else if(smartParkAttendanceApproveQO.getApproveStatus() == 4){
                handleText = "已撤销";
            }
            smartParkAttendanceApprove.setApproveOpinion(handleText);*/
            int update = smartParkAttendanceApproveMapper.updateByPrimaryKey(smartParkAttendanceApprove);
            Long id = smartParkAttendanceApprove.getId();
            if(update>0){
                //判断审批结束后
                if(smartParkAttendanceApprove.getApproveStatus()==2){
                //如果为补卡类型那么修改考勤记录
                    if(smartParkAttendanceApprove.getApproveType()==3){
                        SmartParkAttendanceRecord smartParkAttendanceRecord = smartParkAttendanceRecordMapper.selectByPrimaryKey(smartParkAttendanceApprove.getRepairCardRecordId());
                        if(smartParkAttendanceRecord!=null){
                            smartParkAttendanceRecord.setClockInStatus(1);
                            smartParkAttendanceRecord.setClockInStatusName("补卡");
                            String[] splitStrings = smartParkAttendanceRecord.getShiftWorkTime().split(":");
                            String hour = splitStrings[0];
                            String minute = splitStrings[1];
                            Date handle = DateTimeUtil.handle(smartParkAttendanceRecord.getClockInTime(), Integer.valueOf(hour), Integer.valueOf(minute));
                            smartParkAttendanceRecord.setClockInTime(handle);
                            if(id != null){
                                smartParkAttendanceRecord.setSupplement(id);
                            }
                            smartParkAttendanceRecord.setAbnormalMinutes(0);
                            smartParkAttendanceRecordMapper.updateByPrimaryKey(smartParkAttendanceRecord);
                        }
                    }else {
                        SmartParkAttendanceUserOccupy smartParkAttendanceUserOccupy = new SmartParkAttendanceUserOccupy();
                        smartParkAttendanceUserOccupy.setUserId(smartParkAttendanceApprove.getUserId());
                        smartParkAttendanceUserOccupy.setBusinessType(smartParkAttendanceApprove.getApproveType() == 1?"请假":"出差");
                        smartParkAttendanceUserOccupy.setStartTime(smartParkAttendanceApprove.getStartTime());
                        smartParkAttendanceUserOccupy.setBusinessId(smartParkAttendanceApprove.getId());
                        smartParkAttendanceUserOccupy.setEndTime(smartParkAttendanceApprove.getEndTime());
                        smartParkAttendanceUserOccupy.beforeInsert();
                        smartParkAttendanceUserOccupyMapper.insert(smartParkAttendanceUserOccupy);
                    }
                }
            }
            return ResponseBodyWrapperUtil.toResData(update);
        } catch (Exception e) {
            logger.error("",e);
            return ResponseBodyWrapperUtil.fail(ErrMsgEnum.ERROR_SYSTEM.getErrorMessage(),ErrMsgEnum.ERROR_SYSTEM.getErrorCode());
        }
    }

}
